# coding: utf-8
# @Author : lryself
# @Date : 2020/12/11 0:25
# @Software: PyCharm
from sqlalchemy import and_

from .. import db
from ..utils import commons
from ..utils.response_code import RET

t_newspaper_order_main_view = db.Table(
    'newspaper_order_main_view',
    db.Column('UserID', db.String(20)),
    db.Column('UserName', db.String(255)),
    db.Column('DepartmentID', db.String(20)),
    db.Column('DepartmentName', db.String(255)),
    db.Column('NewspaperID', db.String(20)),
    db.Column('NewspaperName', db.String(255)),
    db.Column('Price', db.Float(20)),
    db.Column('Number', db.Integer, server_default=db.FetchedValue())
)


class NewspaperOrderMainView:
    @classmethod
    def get_order_info_by_newspaper_ID(cls, **kwargs):
        newspaperID = kwargs.get('NewspaperID')
        tag_name = kwargs.get('tag')
        keyword = kwargs.get('keyword')

        filter_list = []
        if "Name" in tag_name or "ID" in tag_name:
            filter_list.append(t_newspaper_order_main_view.columns[tag_name].contains(keyword))
        elif tag_name == "Price":
            filter_list.append(and_(t_newspaper_order_main_view.columns[tag_name] >= float(keyword.split(",")[0]),
                                    t_newspaper_order_main_view.columns[tag_name] <= float(keyword.split(",")[1])))
        else:
            filter_list.append(t_newspaper_order_main_view.columns[tag_name] == keyword)

        filter_list.append(t_newspaper_order_main_view.columns["NewspaperID"] == newspaperID)

        try:
            result_list = db.session.query(t_newspaper_order_main_view).filter(*filter_list)
        except Exception as e:
            return {"code": RET.DBERR, "message": "查询出错", "error": str(e)}

        if not result_list.first():
            return {"code": RET.OK, "message": "暂无数据", "data": []}

        return {"code": RET.OK, "message": "查询成功！", "data": commons.query_to_dict(result_list.all())}

    @classmethod
    def get_info_by_tags(cls, **kwargs):
        tag_name = kwargs.get('tag')
        keyword = kwargs.get('keyword')

        filter_list = []
        if "Name" in tag_name:
            filter_list.append(t_newspaper_order_main_view.columns[tag_name].like('%'+keyword+'%'))
        elif tag_name == "Price":
            filter_list.append(and_(t_newspaper_order_main_view.columns[tag_name] >= float(keyword.split(",")[0]), t_newspaper_order_main_view.columns[tag_name] <= float(keyword.split(",")[1])))
        else:
            filter_list.append(t_newspaper_order_main_view.columns[tag_name] == keyword)

        try:
            result_list = db.session.query(t_newspaper_order_main_view).filter(*filter_list)
        except Exception as e:
            return {"code": RET.DBERR, "message": "查询出错", "error": str(e)}

        if not result_list.first():
            return {"code": RET.OK, "message": "暂无数据", "data": []}

        return {"code": RET.OK, "message": "查询成功！", "data": commons.query_to_dict(result_list.all())}